package com.leetcode.partition1;

import com.leetcode.common.ListNode;

/**
 * @author `RKC`
 * @date 2021/8/3 10:23
 */
public class LC24两两交换链表中的节点 {

    public static ListNode swapPairs(ListNode head) {
        return recursion(head);
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(3);
        l1.next.next.next = new ListNode(4);
        l1 = swapPairs(l1);
        System.out.println(l1.val);
    }

    //递归法
    private static ListNode recursion(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode nextNode = head.next;
        head.next = recursion(head.next.next);
        nextNode.next = head;
        return nextNode;
    }

    //迭代法
    private static ListNode iteration(ListNode head) {
        ListNode result = new ListNode(0);
        result.next = head;
        ListNode current = result;
        while (current.next != null && current.next.next != null) {
            ListNode nextNode = head.next;
            ListNode temp = head.next.next;

            //交换
            current.next = nextNode;
            nextNode.next = head;
            head.next = temp;

            current = head;
            head = head.next;
        }
        return result.next;
    }
}
